package com.ds.robot.assistant.job;

import com.google.common.cache.LoadingCache;
import com.google.common.collect.Lists;
import com.ds.robot.assistant.entity.QxUserEntity;
import com.ds.robot.assistant.model.QxUserResp;
import com.ds.robot.assistant.service.QxUserApiService;
import com.ds.robot.assistant.service.QxUserService;
import com.ds.robot.assistant.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 作用：
 *
 * @author WeiShaoying
 * 
 */
@Component
@Slf4j
@SuppressWarnings("SpellCheckingInspection")
public class QxUserJob {

    @Autowired
    private QxUserApiService userApiService;

    @Resource
    private LoadingCache<String, String> qxUserCache;

    @Autowired
    private QxUserService qxUserService;

    @Transactional(rollbackFor = Exception.class)
    public void firstInsert() {
        List<QxUserResp> userRespList = userApiService.queryAllUsers();
        if (userRespList != null && !userRespList.isEmpty()) {
            List<QxUserEntity> userList = userRespList.stream().map(user -> {
                QxUserEntity qxUser = new QxUserEntity();
                qxUser.setName(user.getName());
                qxUser.setUserid(user.getUserid());
                return qxUser;
            }).collect(Collectors.toList());
            log.info("API查询到的用户数量：{}", userList.size());
            //分批插入，每次30条
            for (int i = 0; i < userList.size(); i += 30) {
                int endIndex = Math.min(i + 30, userList.size());
                List<QxUserEntity> subList = userList.subList(i, endIndex);
                log.info("批量插入用户数据，开始索引:{},结束索引:{}", i, endIndex);
                qxUserService.saveBatch(subList);
            }
        }
    }

    @PostConstruct
    public void init() {
        updateUserCache();
    }

    @Scheduled(cron = "0 5 2/8 * * *")
    @Transactional(rollbackFor = Exception.class)
    public void updateProjectJob() throws Exception {
        List<QxUserResp> userRespList = userApiService.queryAllUsers();
        if (CollectionUtils.isEmpty(userRespList)) {
            log.warn("查询企信人员为空，任务结束");
            return;
        }
        List<QxUserEntity> userList = userRespList.stream().map(user -> {
            QxUserEntity qxUser = new QxUserEntity();
            qxUser.setName(user.getName());
            qxUser.setUserid(user.getUserid());
            return qxUser;
        }).collect(Collectors.toList());

        List<QxUserEntity> dbList = qxUserService.list();
        Map<String, QxUserEntity> entityMap = new HashMap<>();

        if (!CollectionUtils.isEmpty(dbList)) {
            entityMap = dbList.stream().collect(Collectors.toMap(QxUserEntity::getUserid, Function.identity()));
        }

        List<QxUserEntity> needSaveList = Lists.newArrayList();
        List<QxUserEntity> needUpdateList = Lists.newArrayList();
        // 接口查询到的用户id
        List<String> idList = userList.stream().map(QxUserEntity::getUserid).collect(Collectors.toList());
        List<String> needDeleteList = entityMap.keySet().stream().filter(id -> !idList.contains(id)).collect(Collectors.toList());

        for (QxUserEntity entity : userList) {
            if (!entityMap.containsKey(entity.getUserid())) {
                needSaveList.add(entity);
            } else {
                QxUserEntity qxUserDB = entityMap.get(entity.getUserid());
                if (!qxUserDB.equals(entity)) {
                    entity.setId(qxUserDB.getId());
                    needUpdateList.add(entity);
                }
            }
        }

        if (!CollectionUtils.isEmpty(needSaveList)) {
            boolean b = qxUserService.saveBatch(needSaveList);
            log.info("批量新增企业用户成功? {}，数量={}", b, needSaveList.size());
        }
        if (!CollectionUtils.isEmpty(needUpdateList)) {
            log.info("需要更新的企业用户：{}", JsonUtil.toJson(needUpdateList));
            boolean b = qxUserService.saveOrUpdateBatch(needUpdateList);
            log.info("批量更新企业用户成功? {}，数量={}", b, needUpdateList.size());
        }
        if (!CollectionUtils.isEmpty(needDeleteList)) {
            log.info("需要删除的企业用户：{}", JsonUtil.toJson(needDeleteList));
            // boolean b = qxUserService.lambdaUpdate().in(QxUserEntity::getUserid, needDeleteList).remove();
            // log.info("批量删除企业用户成功? {}，数量={}", b, needUpdateList.size());
        }
    }

    @Scheduled(cron = "0 30 2/8 * * *")
    public void updateUserCache() {
        log.info("====开始更新QxUserCache");
        List<QxUserEntity> userList = qxUserService.list();
        if (!CollectionUtils.isEmpty(userList)) {
            for (QxUserEntity entity : userList) {
                qxUserCache.put(entity.getName(), entity.getUserid());
            }
        }
        log.info("====更新QxUserCache完成");
    }

}
